<template>
  <div class="product-detail">
    <el-steps style="padding:30px 300px;background-color:#fff;" :active="active" finish-status="success">
      <el-step title="商品基本信息" />
      <el-step title="添加库存信息" />
      <el-step title="添加移动端详情" />
    </el-steps>

    <el-card shadow="never" class="margin-30">
      <el-form ref="form" :model="product" :rules="rules" label-width="100px" size="mini">
        <div v-show="active==1">
          <div style="font-size:15px;line-height:20px;">基本信息</div>
          <el-divider />
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="商品名称" size="mini" prop="name">
                <el-input v-model="product.name" placeholder="商品名称" size="mini" />
              </el-form-item>
            </el-col>

            <el-col :span="8" :offset="0">
              <el-form-item label="商品编码" size="mini" prop="productSn">
                <el-input v-model="product.productSn" placeholder="商品编码" size="mini" />
              </el-form-item>
            </el-col>

            <el-col :span="8" :offset="0">
              <el-form-item label="商品分类" size="mini" prop="productCategoryId">
                <el-select v-model="product.productCategoryId" placeholder="商品分类" clearable filterable @change="chooseCategory">
                  <el-option
                    v-for="item in productCategory"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="商品品牌" size="mini" prop="brandId">
                <el-select v-model="product.brandId" style="width:100%;" placeholder="品牌" clearable filterable @change="chooseBrand">
                  <el-option
                    v-for="item in brandList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>

            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="15" :offset="0">
              <el-form-item label="商品描述" size="mini">
                <el-input v-model="product.description" :rows="3" type="textarea" placeholder="商品描述" />
              </el-form-item>

            </el-col>
          </el-row>

          <div style="font-size:15px;line-height:20px;">商品属性</div>
          <el-divider />
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="商品原价" size="mini" prop="originalPrice">
                <el-input-number
                  v-model="product.originalPrice"
                  style="width:100%"
                  size="mini"
                  :controls="true"
                  controls-position="both"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8" :offset="0">
              <el-form-item label="促销类型" size="mini">
                <el-select v-model="product.promotionType" disabled style="width:100%;" placeholder="请选择促销类型" clearable filterable>
                  <el-option
                    v-for="item in promotionType"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8" :offset="0">
              <el-form-item label="活动价格" size="mini">
                <el-input-number
                  v-model="product.promotionPrice"
                  disabled
                  style="width:100%"
                  size="mini"
                  :controls="true"
                  controls-position="both"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="重量" size="mini" prop="weight">
                <el-input-number
                  v-model.number="product.weight"
                  style="width:100%"
                  size="mini"
                  :controls="true"
                  controls-position="both"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="审核状态" size="mini">
                <el-switch v-model="product.verifyStatus" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>

            <el-col :span="8" :offset="0">
              <el-form-item label="是否上架" size="mini">
                <el-switch v-model="product.publishStatus" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="缩略图" size="mini" prop="pic">
                <el-upload
                  ref="imgUpload"
                  class="avatar-uploader"
                  :action="uploadImageUrl"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :headers="token"
                >
                  <img v-if="product.pic" :src="product.pic" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </el-form-item>

            </el-col>
          </el-row>

          <div style="font-size:15px;line-height:20px;">其他信息</div>
          <el-divider />
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="推荐状态" size="mini">
                <el-switch v-model="product.recommendStatus" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>

            <el-col :span="8" :offset="0">
              <el-form-item label="新品状态" size="mini">
                <el-switch v-model="product.newStatus" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>

            <el-col :span="8" :offset="0">
              <el-form-item label="预告商品" size="mini">
                <el-switch v-model="product.previewStatus" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="搜索关键词" size="mini">
                <el-input v-model="product.keywords" placeholder="关键词" size="mini" clearable />
              </el-form-item>
            </el-col>

            <el-col :span="8" :offset="0">
              <el-form-item label="库存预警" size="mini" prop="lowStock">
                <el-input-number
                  v-model="product.lowStock"
                  style="width:100%"
                  size="mini"
                  :controls="true"
                  controls-position="both"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8" :offset="0">
              <el-form-item label="商品排序" size="mini" prop="sort">
                <el-input-number
                  v-model="product.sort"
                  style="width:100%"
                  size="mini"
                  :controls="true"
                  controls-position="both"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="产品服务" size="mini">
                <!-- 以逗号分割的产品服务：1->无忧退货；2->快速退款；3->免费包邮 , -->
                <el-checkbox-group v-model="product.serviceIds">
                  <el-checkbox :label="1">无忧退货</el-checkbox>
                  <el-checkbox :label="2">快速退款</el-checkbox>
                  <el-checkbox :label="3">免费包邮</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div v-show="active===2">
          <div style="font-size:15px;line-height:20px;">商品sku信息</div>
          <el-divider />
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="标题" size="mini" prop="detailTitle">
                <el-input v-model="product.detailTitle" placeholder="标题" size="mini" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="副标题" size="mini" prop="detailDesc">
                <el-input v-model="product.detailDesc" placeholder="副标题" size="mini" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="画册图片" size="mini" prop="albumPics">
                <el-upload
                  ref="albumPicsUpload"
                  list-type="picture-card"
                  class="avatar-uploader"
                  :action="uploadImageUrl"
                  :on-success="handleAlbumPicsSuccess"
                  :before-upload="beforeAvatarUpload"
                  :headers="token"
                  :on-exceed="exceedLimit"
                  multiple
                  :limit="maxAlbumPicLen"
                  :disabled="albumPicDisabled"
                  @click.native="exceedLimit"
                >
                  <i slot="default" class="el-icon-plus" />
                  <div slot="file" slot-scope="{file}">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    >
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <i class="el-icon-zoom-in" />
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                      >
                        <i class="el-icon-delete" />
                      </span>
                    </span>
                  </div>
                  <div slot="tip" class="el-upload__tip">只能上传图片文件,且不超过1M</div>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl">
                </el-dialog>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="sku设置" size="mini">
                <div>
                  <el-row v-for="(item,indexItem) in sku" v-show="item.arr.length" :key="item.name" style="height:fit-content;" :gutter="0">
                    <el-col :span="24" :offset="0">
                      <el-form-item label-width="50px" :label="`${item.name}:`" size="mini">
                        <el-checkbox-group v-model="item.selectedArr">
                          <el-checkbox v-for="(skuItem,itemIndex) in item.arr" :key="skuItem" :label="skuItem">
                            {{ skuItem }} <span style="color:red;" @click="deleteSkuItem(indexItem,itemIndex)">删除</span>
                          </el-checkbox>
                        </el-checkbox-group>
                      </el-form-item>

                    </el-col>
                  </el-row>
                </div>
                <el-row :gutter="0">
                  <el-col :span="18" :offset="0">
                    <div class="sku">
                      <div v-for="(item,indexSku) in sku" :key="item.name" style="margin-right:10px;margin-bottom:15px;">
                        <el-input v-model="item.input" style="display:inline-block;width:200px;margin-right:10px;" :placeholder="`${item.name}描述：比如${item.example}`" size="small" />
                        <el-button size="mini" @click="generateSkuItem(indexSku)">创建{{ item.name }}选项</el-button>
                      </div>
                    </div>
                  </el-col>
                  <el-col :span="6" :offset="0">
                    <el-button type="primary" size="mini" @click="makeSkuList">生成sku列表</el-button>
                    <el-button type="primary" size="mini" @click="addSku">新增sku</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>

          <el-table v-show="pmsSkuStockList.length" style="margin-left:100px;" :data="pmsSkuStockList" border stripe>
            <el-table-column
              fixed="left"
              type="index"
              label="#"
              width="50"
              align="center"
            />

            <el-table-column
              label="图片"
              width="150"
              align="center"
            >
              <template slot-scope="scope">
                <!-- style="width:100px;height:100px;" -->
                <el-upload
                  :ref="'upload'+scope.$index"
                  class="avatar-uploader"
                  :action="uploadImageUrl"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :headers="token"
                  :show-file-list="false"
                  @click.native="handleRef(index,scope.row.id)"
                >
                  <img v-if="scope.row.pic" style="display:block;width:100px;height:100px;" :src="scope.row.pic" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </template>
            </el-table-column>

            <el-table-column
              v-for="item in sku"
              :key="item.name"
              align="center"
              :label="item.name"
              width="200"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row[item.type]" :placeholder="item.name" size="mini" />

              </template>
            </el-table-column>
            <el-table-column
              label="库存"
              width="200"
              align="center"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.stock" placeholder="自定义库存" size="mini" />
              </template>
            </el-table-column>

            <el-table-column
              label="预警库存"
              width="200"
              align="center"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.lowStock" placeholder="库存预警" size="mini" />
              </template>
            </el-table-column>

            <el-table-column
              label="库存锁定"
              width="200"
              align="center"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.lockStock" placeholder="库存锁定" size="mini" />
              </template>
            </el-table-column>

            <el-table-column
              label="sku编码"
              width="200"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuCode" placeholder="sku编码" size="mini" />
              </template>
            </el-table-column>

            <el-table-column
              label="价格"
              width="200"
              align="center"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" placeholder="价格" size="mini" />
              </template>
            </el-table-column>

            <el-table-column
              label="销量"
              width="200"
              align="center"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.sale" placeholder="销量" size="mini" />
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              label="操作"
              width="150"
            >
              <template slot-scope="scope">
                <el-button type="text" style="color:red;" size="mini" @click="deleteSku(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>

          </el-table>

        </div>
        <div v-show="active===3">
          <div style="font-size:15px;line-height:20px;">详情描述</div>
          <el-divider />
          <el-form-item label="商品详情" size="mini">
            <Tinymce v-model="product.detailMobileHtml" style="margin-top:20px" />
          </el-form-item>
          <el-form-item label="备注" size="mini">
            <el-row :gutter="20">
              <el-col :span="20" :offset="0">
                <el-input
                  v-model="product.note"
                  type="textarea"
                  :rows="3"
                  placeholder="备注"
                />
              </el-col>
            </el-row>

          </el-form-item>

        </div>
      </el-form>
      <el-row style="margin-top:40px;" type="flex" justify="center" :gutter="20">
        <el-col v-if="active!==1" :span="2" style="margin-right:20px;" :offset="0">
          <el-button size="mini" @click="prev">返回上一步</el-button>
        </el-col>
        <el-col :span="4" :offset="0">
          <el-button size="mini" type="primary" @click="next">{{ nextInfo[active-1] }}</el-button>
        </el-col>
      </el-row>

    </el-card>

  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import {
  getAllCategory as getAllCategoryApi,
  findAllBrand as findAllBrandApi,
  addProductAndSkus as addProductAndSkusApi,
  productSkusDetail as productSkusDetailApi,
  updateProductAndSkus as updateProductAndSkusApi

} from '@/api/product/list'
import mix from '@/mixin'
import { v4 as uuidv4 } from 'uuid'
export default {
  name: 'ProductDetail',
  components: {
    Tinymce
  },
  mixins: [mix],
  data() {
    return {
      rules: {
        name: [{ required: true, trigger: 'blur', message: '请填写商品名称' }],
        originalPrice: [
          { required: true, trigger: 'blur', message: '请填写商品原价' },
          { pattern: /^\+?[1-9]\d*$/, trigger: 'blur', message: '商品原价必须大于0的数字' }],
        productCategoryId: [{ required: true, trigger: 'blur', message: '请选择商品分类' }],
        weight: [
          { required: true, trigger: 'blur', message: '请输入商品重量' },
          { pattern: /^\+?[1-9]\d*$/, trigger: 'blur', message: '商品重量必须大于0的数字' }
        ],
        sort: [
          { required: true, trigger: 'blur', message: '请输入商品排序' },
          { pattern: /^\+?[1-9]\d*$/, trigger: 'blur', message: '商品排序必须大于0的数字' }
        ],
        lowStock: [
          { required: true, trigger: 'blur', message: '请输入商品库存预警' },
          { pattern: /^\+?[1-9]\d*$/, trigger: 'blur', message: '商品库存预警必须大于0的数字' }
        ],
        productSn: [{ required: true, trigger: 'blur', message: '请输入商品编码' }],
        brandId: [{ required: true, trigger: 'blur', message: '请选择商品品牌' }],
        pic: [{ required: true, trigger: 'blur', message: '请选择商品展示缩略图' }],
        detailTitle: [{ required: true, trigger: 'blur', message: '请选择商品标题' }],
        detailDesc: [{ required: true, trigger: 'blur', message: '请选择商品副标题' }],
        albumPics: [{ type: 'array', required: true, min: 1, message: '画册个数在1-5之间' }]
      },
      pmsSkuStockList: [], // sku库存设置
      maxAlbumPicLen: 5, // 画册最大上传个数
      albumPicDisabled: false,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      productId: '', // 商品ID
      active: 1, // 步骤条选中
      nextInfo: ['下一步，填写库存信息', '下一步，填写移动端详情', '提交保存'],
      product: {
        originalPrice: 0, // 原价
        promotionType: 0, // 促销类型
        promotionPrice: 0, // 促销价格
        weight: 0, // 重量
        pic: '', // 缩略图
        lowStock: 0, // 库存预警
        sort: 0, // 商品排序
        serviceIds: [], // 后期处理成字符串，以逗号分割
        albumPics: [], // 画册图片，连产品图片限制为5张，以逗号分割 ,会在移动端商品详情页展示
        giftGrowth: 0, // 赠送的成长值(预留)
        giftPoint: 0, // 赠送的积分(预留)
        promotionEndTime: '', // 可以不填. 促销结束时间 ,可以通过营销管理修改
        promotionPerLimit: 0, // 活动限量个数
        unit: '个', // 单位,比如 斤/辆/台
        newStatus: 0, // 新品状态
        previewStatus: 0, // 是否为预告商品
        publishStatus: 0, // 上架状态
        recommendStatus: 0, // 推荐状态
        verifyStatus: 0// 审核状态
      },
      productCategory: [], // 商品分类
      brandList: [], // 商品品牌
      promotionType: [// 0->没有促销使用原价;1->使用促销价；2->使用会员价；3->使用阶梯价格；4->使用满减价格；5->限时购
        {
          id: 0,
          label: '没有促销使用原价'
        },
        {
          id: 1,
          label: '使用促销价'
        },
        {
          id: 2,
          label: '使用会员价'
        },
        {
          id: 3,
          label: '使用阶梯价格'
        },
        {
          id: 4,
          label: '使用满减价格'
        },
        {
          id: 5,
          label: '限时购'
        }

      ],

      easySku: {
        color: '颜色',
        size: '大小'
      },
      refClickId: '',
      index: 0

    }
  },
  created() {
    this.productId = this.$route.query.productId
    if (this.productId) {
      this.getProductDetail()
    }
    this.getProductCategory()
    this.getBrandList()
  },
  methods: {
    // 获取商品详情
    getProductDetail() {
      productSkusDetailApi(this.productId)
        .then(res => {
          const { message, data, success } = res
          if (success) {
            this.product = data.product
            this.pmsSkuStockList = data.skus
            this.product.serviceIds = this.product.serviceIds.split(',').map(ele => parseInt(ele))
            // this.product.albumPics = this.product.albumPics.split(',')
            this.product.albumPics = this.product.albumPics.split(',').map(ele => {
              var obj = {
                name: '',
                url: ele
              }
              this.$refs.albumPicsUpload.fileList.push(obj)
              return obj
            })
            // sku转化
            for (var i = 0; i < this.pmsSkuStockList.length; i++) {
              var item = this.pmsSkuStockList[i]
              var spData = JSON.parse(item.spData)
              spData.forEach(ele => {
                var skuItem = this.sku.find(el => el.name === ele.key)
                item[skuItem.type] = ele.value
              })
            }
          } else {
            this.$message.error(message)
          }
        })
    },
    // 添加一项sku表格项
    addSku() {
      if (this.sureSkuHas()) {
        this.pmsSkuStockList.push(...this.getSku())
      }
    },
    // sku列表图片ref处理
    handleRef(index, id) {
      this.refClickId = id
      this.index = index
    },
    // 删除sku规格项目
    deleteSku(id) {
      var index = this.pmsSkuStockList.findIndex(ele => ele.id === id)
      this.pmsSkuStockList.splice(index, 1)
    },
    // 判断是否每种规格都被选中
    sureSkuHas() {
      var flag = this.sku.some(ele => ele.selectedArr.length !== 0)
      if (!flag) { // 没有选中一项
        this.$message.error('至少选中一项规格')
      }
      return flag
    },
    getSku() {
      var tempArr = []
      var needArr = []
      for (var i = 0; i < this.sku.length; i++) {
        var itemArr = this.sku[i].selectedArr
        var key = this.sku[i].type
        tempArr = needArr

        if (!itemArr.length) {
          continue
        } else {
          needArr = []
        }
        if (!tempArr.length) { // 如果暂时的数组为空
          tempArr = itemArr.map(ele => {
            var obj = {
              [key]: ele
            }
            return obj
          })
          needArr = tempArr
        } else { // 暂时数组不为空
          for (var j = 0; j < tempArr.length; j++) {
            var item = tempArr[j]
            for (var k = 0; k < itemArr.length; k++) {
              item[key] = itemArr[k]
              const obj = {}
              for (var keys in item) {
                obj[keys] = item[keys]
              }
              needArr.push(obj)
            }
          }
        }
      }
      needArr.forEach(ele => {
        Object.assign(ele, {
          id: uuidv4(),
          'lockStock': 0, // 锁定库存
          'lowStock': 10, // 库存警戒线
          'pic': '', // 图片
          'price': 0, // 当前价格
          'promotionPrice': 0, // 单品促销价格
          'sale': 0, // 销量
          'skuCode': '', // sku的编码,手动填写
          // spData:  [{"key":"颜色","value":"蓝色"},{"key":"容量","value":"32G"}]
          'spData': [], // sku属性，json格式String类型 ,
          'stock': 0
        })
      })
      return needArr
    },
    // 生成sku列表
    makeSkuList() {
      if (!this.sureSkuHas()) { return }
      this.$confirm('此操作将清空sku列表,并生成新的列表, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '创建成功!'
        })
        this.pmsSkuStockList = this.getSku()
      })
    },
    // 删除一个规格项目
    deleteSkuItem(index, itemIndex) {
      var item = this.sku[index]
      var value = item.arr[itemIndex]
      var selectIndex = item.selectedArr.findIndex(ele => ele === value)
      item.selectedArr.splice(selectIndex, 1)
      item.arr.splice(itemIndex, 1)
    },
    // 点击生成一个规格项目
    generateSkuItem(index) {
      var item = this.sku[index]
      if (item.input.length !== 0) {
        item.arr.push(item.input)
        item.input = ''
      }
    },
    // 画册超出最大值
    exceedLimit() {
      if (this.product.albumPics.length === this.maxAlbumPicLen) {
        this.$message.error(`上传图片失败,最多只能上传${this.maxAlbumPicLen}张图片`)
      }
    },
    // 删除画册
    handleRemove(file) {
      var files = this.$refs.albumPicsUpload.uploadFiles
      console.log('foles==>', files)
      var index = files.findIndex(ele => ele.uid === file.uid)
      var url = files[index].url
      files.splice(index, 1)
      // var url = file.response.data.fileUrl
      // index = this.product.albumPics.findIndex(ele => ele === url)
      index = this.product.albumPics.findIndex(ele => {
        if (typeof (ele) === 'object') {
          return ele.url === url
        } else {
          return ele === url
        }
      })
      this.product.albumPics.splice(index, 1)
    },
    // 画册图像预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 画册图片文件上传成功时候的钩子函数
    handleAlbumPicsSuccess(res, file, fileList) {
      const { success, message, data } = res
      if (success) {
        this.product.albumPics.push(data.fileUrl)
      } else {
        this.$message.error(message)
      }
    },
    // 缩略图文件上传成功时候的钩子函数
    handleAvatarSuccess(res, file, fileList) {
      const { success, message, data } = res
      if (success) {
        if (this.refClickId) {
          var item = this.pmsSkuStockList.find(ele => ele.id === this.refClickId)
          item.pic = data.fileUrl
          this.$refs['upload' + this.index].clearFiles()
          this.refClickId = ''
        } else {
          this.product.pic = data.fileUrl
          this.$refs.imgUpload.clearFiles()
        }
      } else {
        this.$message.error(message)
      }
    },
    // 在文件上传之前的钩子函数
    beforeAvatarUpload(file) {
      if (this.product.albumPics.length === this.maxAlbumPicLen - 1) {
        this.albumPicDisabled = true
      }
      const isLt1dot5M = file.size / 1024 / 1024 < 1.5
      var reg = /^image\/(jpe?g|png|webp|gif)$/

      const isImage = reg.test(file.type)
      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt1dot5M) {
        this.$message.error('上传头像图片大小不能超过 1.5MB!')
      }
      return isImage && isLt1dot5M
    },
    // 选择商品品牌
    chooseBrand(e) {
      var item = this.brandList.find(ele => ele.id === e)
      this.product.brandName = item.name
    },
    // 获取品牌列表
    getBrandList() {
      findAllBrandApi()
        .then(res => {
          const { message, data, success } = res
          if (success) {
            this.brandList = data.items
          } else {
            this.$message.error(message)
          }
        })
    },
    // 选择商品分类
    chooseCategory(e) {
      var item = this.productCategory.find(ele => ele.id === e)
      this.product.productCategoryName = item.name
    },
    // 获取商品分类
    getProductCategory() {
      getAllCategoryApi()
        .then(res => {
          const { message, success, data } = res
          if (success) {
            var item = data.items.find(ele => ele.category.name === '乐居')
            this.productCategory = item.children
          } else {
            this.$message.error(message)
          }
        })
    },
    getRuleResult(arr) {
      var errorArr = []
      this.$refs.form.validateField(arr, error => {
        errorArr.push(error)
      })
      for (var i = 0; i < errorArr.length; i++) {
        if (errorArr[i]) {
          this.$message.error(errorArr[i])
          return false
        }
      }
      return true
    },
    // 点击下一步
    next() {
      var orderRuleProps = null
      if (this.active === 1) {
        orderRuleProps = ['name', 'originalPrice', 'productCategoryId', 'weight', 'sort', 'lowStock', 'productSn', 'brandId', 'pic']
        if (this.getRuleResult(orderRuleProps)) {
          this.active++
        }
      } else if (this.active === 2) {
        orderRuleProps = ['detailDesc', 'detailTitle', 'albumPics']
        if (this.getRuleResult(orderRuleProps)) {
          this.active++
        }
      } else if (this.active === 3) {
        var api = null
        if (this.productId) {
          api = updateProductAndSkusApi
          this.product.id = this.productId
        } else {
          api = addProductAndSkusApi
        }
        this.product.serviceIds = this.product.serviceIds.join(',')
        // 格式化相册
        this.product.albumPics = this.product.albumPics.map(ele => {
          if (typeof (ele) === 'object') {
            return ele.url
          } else {
            return ele
          }
        })
        this.product.albumPics = this.product.albumPics.join(',')
        this.product.price = this.product.promotionPrice
        // sku格式化
        for (var j = 0; j < this.pmsSkuStockList.length; j++) {
          const item = this.pmsSkuStockList[j]
          if (this.productId) {
            item.productId = this.productId
          } else {
            delete item.id
          }
          item.spData = []
          for (let i = 0; i < this.sku.length; i++) {
            var key = this.sku[i].type
            var name = this.sku[i].name
            item.spData.push({ key: name, value: item[key] })
          }
          item.spData = JSON.stringify(item.spData)
        }
        // 商品规格格式化
        var uploadObj = {
          pmsSkuStockList: this.pmsSkuStockList,
          product: this.product
        }

        api(uploadObj)
          .then(res => {
            const { success, message } = res
            if (success) {
              if (this.productId) {
                this.$message.success('修改商品成功！')
              } else {
                this.$message.success('新增商品成功！')
              }
              this.$router.push({ name: 'ProductList' })
            } else {
              this.$message.error(message)
            }
          })
      }

      // albumPics:画册图片，后期换成字符串,以逗号分割
    },
    // 返回到上一步
    prev() {
      if (this.active !== 1) {
        this.active--
      }
    }
  }
}
</script>

<style lang="scss" scoped>
 ::v-deep .el-divider {
    margin-top: 10px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin:0 auto;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .product-detail{
    .sku{
      display: flex;
      flex-wrap: wrap;
      width: 100%;
    }
    ::v-deep .btn{
      display: none;
    }
    ::v-deep .upload-container{
      display: none;
    }
  }

 ::v-deep  img.el-upload-list__item-thumbnail{
    display: block;
    width: 146px;
    height: 146px;
  }
</style>
